<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 产品管理
 * @author khj
 */
class Product extends MY_Controller {
    /**
     * @var ConsumerCategoryModel
     */
    public $mCat = null;
    /**
     * @var ConsumerProductModel
     */
    public $mProduct = null;
    /**
     * @var AdmSettingModel
     */
    public $mSetting = null;

	public function __construct(){

		parent::__construct();
	}

    /**
     * 平台一级分类
     */
    public function category(){
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');

        $tA = $this->mCat->getCategoryList(0, true, $this->userCategoryId);

        $this->appReturn(1, '', $tA);
    }

    /**
     * 平台二级分类
     */
    public function childCategory(){
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');
        //表单验证
        $vConf = array(
            array('id', '分类id', 'required|is_numeric'),

        );
        $this->formDataValidation($vConf);

        $parent_id = (int)post('id');

        $tA = $this->mCat->getCategoryList($parent_id, true, $this->userCategoryId);

        $this->appReturn(1, '', $tA);
    }

    /**
     * 添加商品分类
     */
    public function addCategory(){
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');

        //表单验证
        $vConf = array(
            array('cat_name', '分类名称', 'required'),
            array('parent_id', '平台一级分类id', 'required|is_numeric'),
            array('category_id', '平台二级分类id', 'required|is_numeric'),

        );
        $this->formDataValidation($vConf);

        $cat_name = trim(post('cat_name'));
        $id = (int)post('id');
        $parent_id = post('parent_id');
        $category_id = post('category_id');

        //判断分类名称是否存在
        $info = $this->mCat->getCategoryInfoByName($cat_name, $this->userId, $id);
        if($info){
            $this->appReturn(0, '分类名称已存在');
        }

        //判断一二级分类是否存在
        $cats = $this->mCat->getInfoByIds(array($parent_id,$category_id));

        if(!isset($cats[$parent_id]['cat_name'])){
            $this->appReturn(0, '一级分类不存在');
        }

        if(!isset($cats[$category_id]['cat_name'])){
            $this->appReturn(0, '二级分类不存在');
        }

        $data = array(
            'merchant_id' => $this->userId,
            'parent_id' => $parent_id,
            'category_id' => $category_id,
            'cat_name' => $cat_name,
            'status' => 2,
            'addtime' => time(),

        );

        //保存自定义分类
        if(!($this->mCat->saveCustom($data, $id))){
            $this->appReturn(0, '保存失败');
        }

        $this->appReturn(1, '保存成功');
    }

    /**
     * 自定义分类详情
     */
    public function customCategoryInfo(){
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');
        //表单验证
        $vConf = array(
            array('id', '分类id', 'required|is_numeric'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');

        //判断分类名称是否存在
        $info = $this->mCat->getCustomInfo($id, $this->userId);
        if(!$info){
            $this->appReturn(0, '分类名称不存在');
        }

        //获取分类名称
        $cat = $this->mCat->getInfoByIds(array($info['parent_id'],$info['category_id']));

        $info['parent'] = isset($cat[$info['parent_id']]['cat_name'])?$cat[$info['parent_id']]['cat_name']:'';
        $info['category'] = isset($cat[$info['category_id']]['cat_name'])?$cat[$info['category_id']]['cat_name']:'';

        unset($info['merchant_id'],$info['status']);
        $this->appReturn(1, '', $info);
    }

    /**
     * 删除自定义分类
     */
    public function delCustomCategory(){
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        //表单验证
        $vConf = array(
            array('id', '分类id', 'required|is_numeric'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');

        //判断分类是否存在
        $info = $this->mCat->getCustomInfo($id, $this->userId);
        if(!$info){
            $this->appReturn(0, '分类名称不存在');
        }

        //判断分类下是否存在商品
        $productNumber = $this->mProduct->getCustomProductCount(array($id), $this->userId);
        if(isset($productNumber[$id]) && $productNumber[$id] > 0){
            $this->appReturn(0, '该分类下存在商品,不可删除');
        }

        //删除分类
        if(!($this->mCat->deleteCustomCategory($id, $this->userId))){
            $this->appReturn(0, '删除失败');
        }

        $this->appReturn(1, '删除成功');
    }

    /**
     * 获取全部自定义分类
     */
    public function getAllCategory(){
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');

        //获取分类列表
        $tA = $this->mCat->getCustomList($this->userId);

        $this->appReturn(1, '', $tA);
    }

    /**
     * 获取自定义分类列表
     */
    public function getCategoryList(){
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');

        //获取分类列表
        $tA = $this->mCat->getCustomList($this->userId);
        $tData = array('list' => $tA);

        if($tData['list']){
            $customId = array();
            foreach ($tData['list'] as $k=>$v){
                if(!in_array($v['id'], $customId)){
                    $customId[] = $v['id'];
                }
            }
            //获取商品数量
            $number = $this->mProduct->getCustomProductCount($customId, $this->userId);

            foreach ($tData['list'] as $key=>&$value){
                $value['number'] = isset($number[$value['id']])?$number[$value['id']]:'0';
            }
        }

        $this->appReturn(1, '', $tData);
    }

    /**
     * 自定义分类排序
     */
    public function categorySort(){

        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');

        //表单验证
        $vConf = array(
            array('text', '分类序列', 'required'),
        );
        $this->formDataValidation($vConf);

        $text = trim(post('text'));
        $tData = json_decode(stripslashes($text), true);

        if(!is_array($tData)){
            $this->appReturn(0, '分类序列格式错误');
        }
        foreach ($tData as $v){
            if(!is_numeric($v['sort'])){
                $this->appReturn(0, '序号必须是数字');
            }
        }

        //保存排序
        if(!($this->mCat->saveCustomBatch($tData))){
            $this->appReturn(0, '保存失败');
        }

        $this->appReturn(1, '保存成功');
    }


    /**
     * 添加，编辑商品
     */
    public function addProduct(){

        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        //表单验证
        $vConf = array(
            array('name', '商品名称', 'required'),
            array('goods_price', '商品价格', 'required'),
//            array('market_price', '市场价格', 'required'),
            array('is_limited', '库存设置', 'required|in_list[1,2]'),
            array('is_special', '会员专属', 'required|in_list[1,2]'),
            array('quantity', '库存数量', 'required|is_numeric'),
            array('lunch_box_fee', '餐费费', 'required|is_numeric'),
            array('weight', '商品重量', 'required|is_numeric'),
            array('limit_number', '限购数量', 'is_numeric'),
            array('discount', '折扣', 'required|is_numeric'),
            array('category_id', '分类id', 'required|is_natural_no_zero'),
//            array('is_free_shipping', '包邮状态', 'required|in_list[1,2]'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');
        $property 	= trim(post('property'));//规格组合变体
        $detail	= trim(post('detail'));//商品详情
        $tags	= trim(post('tags'));//属性
        $limit_number = post('limit_number');
        $discount = post('discount');
        $images = json_decode(stripslashes(trim(post('images'))));//轮播图片

        if(!$id && ! $images){
            $this->appReturn(0, '请上传商品轮播图');
        }

        if(!$id && !isset($_FILES['icon']) && empty($_FILES['icon'])){
            $this->appReturn(0, '请上传封面图');
        }

        if($limit_number && !$discount){
            $this->appReturn(0, '请输入折扣');
        }

        if($limit_number == 0 && $discount>0){
            $this->appReturn(0, '请输入限购数量');
        }

        if($id){
            //验证商品是否存在
            $productInfo = $this->mProduct->getInfo($id, $this->userId, false);
            if(!$productInfo){
                $this->appReturn(0, '商品不存在');
            }
        }

        $data = array(
            'merchant_id' => $this->userId,
            'name' => trim(post('name')),
            'subtitle' => trim(post('subtitle')),
            'goods_price' => trim(post('goods_price')),
//            'market_price' => trim(post('market_price')),
            'is_limited' => post('is_limited'),
            'is_special' => post('is_special'),
            'quantity' => post('quantity'),
            'limit_number' => $limit_number>0?$limit_number:0,
            'discount' => $limit_number == 0?0:$discount,
            'category_id' => post('category_id'),
            'lunch_box_fee' => post('lunch_box_fee'),
            'weight' => post('weight'),
            'is_free_shipping' => 1,//post('is_free_shipping'),
            'status' => 1,
        );

        //重量限制
        if($data['weight'] > 1000){
            $this->appReturn(0, '商品重量最大一顿');
        }
        $this->db->trans_begin();
        if(!$id){//新增商品

            $data['addtime'] = time();

            if(!($id = $this->mProduct->save($data))){
                $this->db->trans_rollback();
                $this->appReturn(0, '保存失败');
            }
        }

        //上传封面图
        if(isset($_FILES['icon']) && !empty($_FILES['icon'])){
            $path = 'uploads/product/home/'.$id;

            $tA = imageUpload($path, 'icon', 'icon', true, 250, 250);
            if( ! $tA['status']){
                $this->db->trans_rollback();
                $this->appReturn(0, '封面图上传失败');
            }

            $data['icon'] = $tA['data'];
        }

        //轮播图
        if($images){
            $imgPath = array();
            $path = 'uploads/product/home/'.$id.'/';

            foreach ($images as $k => $v){

                if (stripos($v,'temp') !== FALSE){

                    $res = saveTempImg($v, $path, true);
                    if($res === false){
                        $this->appReturn(0, '临时图片不存在');
                    }
                    $imgPath[] = $res;
                }else{

                    $imgPath[] = str_replace(base_url(), '', $v);
                }
            }

            if( isset($info['img']) ){

                $oldImg = $info['img'];

                foreach ($oldImg as $key=>$v){

                    if( ! in_array($v, $imgPath)){

                        if (stripos($v, '?') !== false){
                            //查找?存在处理
                            $v = strstr($v, '?',true);
                        }

                        $tA = explode('/', $v);
                        $filename = $tA[count($tA)-1];
                        if (file_exists($v)){
                            unlink($v);
                        }

                        if (file_exists($path.'sm/'.$filename)){
                            unlink($path.'sm/'.$filename);
                        }

                        if (file_exists($path.'xs/'.$filename)){
                            unlink($path.'xs/'.$filename);
                        }

                    }
                }
            }

            //轮播图片
            if($imgPath){
                $data['img'] = json_encode($imgPath);
            }
        }


        //商品详情
        $detail = json_decode(stripslashes($detail), true);
        if($detail){

            $tDetail = array();

            foreach ($detail as $k=>$det){
                if(!in_array($det['type'], array(1,2))){
                    $this->appReturn(0, '详情类型错误');
                }
               //如果是图片
                if($det['type'] == 2){
                    $path = 'uploads/product/home/' . $id . '/detail';

                    if (stripos($det['content'],'temp') !== FALSE){
                        $det['content'] = saveTempImg($det['content'], $path, true);
                        if($det['content'] === false){
                            $this->appReturn(0, '临时图片不存在');
                        }
                    }
                    if (stripos($det['content'],'uploads/product/home/') !== FALSE){
                        $det['content'] =  str_replace(base_url(), '', $det['content']);
                    }
                }

                $tDetail[$k] = array(
                    'product_id' => $id,
                    'type' => $det['type'],
                    'content' => $det['content'],
                    'sort' => $k,
                );
            }
            if($tDetail){
                /**
                 * 删除产品所有详情
                 */
                $query = $this->mProduct->removeDetail($id);
                if ( ! $query){
                    $this->db->trans_rollback();
                    $this->appReturn(0,'删除图片失败');
                }
                //保存商品详情
                if(!($this->mProduct->saveDetail($tDetail, 0, 0, true))){
                    $this->db->trans_rollback();
                    $this->appReturn(0, '保存失败');
                }
            }
        }

        //商品属性

        $tags = json_decode(stripslashes($tags), true);

        if($tags){
            //清除所有
            if (! $this->mProduct->removeTags(0,$id)){
                $this->db->trans_rollback();
                $this->appReturn(0,'清除失败,请重新保存');
            }
            $tagData = array();
            foreach ($tags as $k=>$v){
                if(!$v['tag_value']){
                    $this->appReturn(0,'属性值不能为空');
                }
                $tagData[$k]['product_id'] = $id;
                $tagData[$k]['sort'] = $k+1;
                $tagData[$k]['tag_name'] = $v['tag_name'];
                $tagData[$k]['tag_value'] = json_encode($v['tag_value'], JSON_UNESCAPED_UNICODE);
            }

            unset($tags);
            $query = $this->mProduct->saveTags($tagData,true);

            if (! $query){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'保存失败');
            }
        }else{
            //清除所有
            $this->mProduct->removeTags(0,$id);
        }

        /**
         * 规格重置
         */

        $property = json_decode(stripslashes($property), true);
        if ($property){

            $tVariant = array();
            /**
             * 属性
             */
            //清除所有
            if (! $this->mProduct->removeProperty(0,$id)){
                $this->db->trans_rollback();
                $this->appReturn(0,'清除失败,请重新保存');
            }

            $nData = array(
                'product_id' => $id,
                'sort' => 1,
                'lable' => '规格',
                'value' => implode('|', array_column($property, 'property')),
            );

            $query = $this->mProduct->saveProperty($nData,0,false);
            if (! $query){
                $this->db->trans_rollback();
                $this->appReturn(0,'保存失败');
            }

            foreach ($property as $key=>$tValue){

                $pro[1] = $tValue['property'];
                $tValue['quantity'] = isset($tValue['quantity'])?$tValue['quantity']:0;
                $tVariant[] = array(
                    'product_id' => $id,
                    'property' => json_encode($pro, JSON_UNESCAPED_UNICODE),
                    'price' => $tValue['price'],
                    'weight' => isset($tValue['weight'])?$tValue['weight']:0,
                    'is_limited'=> $tValue['is_limited'],
                    'quantity'=> $tValue['quantity'],
                    'sort' => $key+1,
                    'status' => 2,
                    'sale_quantity' => 0,
                );
                if($data['is_limited'] == 1 && $tValue['is_limited'] == 2){
                    $data['is_limited'] = 2;
                }
            }

            if (! $this->mProduct->removePropertyVariant(0,$id)){
                $this->db->trans_rollback();
                $this->appReturn(0,'清除变体失败');
            }

            $query = $this->mProduct->savePropertyVariant($tVariant,0,0,true);
            if (! $query){
                $this->db->trans_rollback();
                $this->appReturn(0,'变体保存失败');
            }
        }else{
            //清空规格

            $this->mProduct->removeProperty(0, $id);
            $this->mProduct->removePropertyVariant(0, $id);
        }
        //保存商品信息
        if(!($this->mProduct->save($data, $id))){
            $this->db->trans_rollback();
            $this->appReturn(0, '保存失败');
        }

        $this->db->trans_commit();
        $this->appReturn(1,'保存成功');
    }


    /**
     * 标签变体
     */
    public function variant(){
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        //表单验证
        $vConf = array(
            array('lable', '标签', 'required'),
        );
        $this->formDataValidation($vConf);

        $lable = trim(post('lable'));

        $tA = json_decode($lable,true);

        $tProperty = array();
        $lable = array();
        foreach ($tA as $k=>$v){

            $lable[$k]['product_id'] = 0;
            $lable[$k]['sort'] = $k+1;
            $lable[$k]['value'] = str_replace(',', '|', $v['value']);

            //获取属性
            $temp = $lable[$k];
            $temp['value'] = explode(',', $v['value']);
            $tProperty[] = $temp;
        }

        $variant = $this->mProduct->setPropertyVariant($tProperty);

        foreach ($variant as $key=>$value){
            $variant[$key] = implode('/',$value);
        }

        $this->appReturn(1, '', $variant);
    }

    /**
     * 商品信息
     */
    public function productInfo(){

        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        $this->loadModel('ConsumerCategoryModel', 'mCat', 'consumer');
        //表单验证
        $vConf = array(
            array('id', '商品id', 'required|is_numeric'),
        );
        $this->formDataValidation($vConf);

        $id = post('id');

        //获取详情
        $info = $this->mProduct->getInfo($id, $this->userId, false, true);
        if(!$info){
            $this->appReturn(0, '商品不存在');
        }
        $catInfo = $this->mCat->getCustomInfo($info['category_id'], $this->userId);
        if(!$catInfo){
            $this->appReturn(0, '分类不存在');
        }
        $info['category'] = $catInfo['cat_name'];

        //获取商品标签
        $lable = $this->mProduct->getPropertyList($id);
        $aDate = array();
        if($lable){
            $aDate = $lable;
        }
        $info['lable'] = $aDate;

        //标签变体
        $variant = $this->mProduct->getPropertyVariantList($id);
        $info['variant'] = array();
        if($variant){
            foreach ($variant as $k=>$v){
                $variant[$k]['property'] = array_column($v['property'],'value');
                $variant[$k]['property_ios'] = implode('/',$variant[$k]['property']);
            }
            $info['variant'] = $variant;
        }

        unset($info['addtime']);
        //商品详情
        $data = $this->mProduct->getDetailList($id);
        $info['detail'] = $data;
        //商品标签
        $tags = $this->mProduct->getTagsList($id);
        $info['tags'] = $tags;
        $this->appReturn(1, '', $info);
    }

    /**
     * 商品详情信息
     */
    public function productDetail(){
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');

        //表单验证
        $vConf = array(
            array('id', '商品id', 'required|is_numeric'),
        );
        $this->formDataValidation($vConf);

        $id = post('id');

        //获取详情
        $info = $this->mProduct->getInfo($id, $this->userId, false);
        if(!$info){
            $this->appReturn(0, '商品不存在');
        }

        $data = $this->mProduct->getDetailList($id);

        $this->appReturn(1, '', $data);
    }


    /**
     * 商品 上架 下架
     */
    public function onSale(){
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        //表单验证
        $vConf = array(
            array('id', '商品id', 'required|is_numeric'),
            array('status', '状态', 'required|in_list[1,2]'),
        );
        $this->formDataValidation($vConf);

        $id = post('id');
        $status= post('status');

        //商品是否存在
        $productInfo = $this->mProduct->getInfo($id, $this->userId, false);
        if(!$productInfo){
            $this->appReturn(0, '商品不存在');
        }

        //保存商品
        if(!($this->mProduct->save(array('status' => $status), $id))){
            $this->appReturn(0, '保存失败');
        }

        $this->appReturn(1, '保存成功');
    }

    /**
     * 商品列表
     */
    public function productList(){
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        //表单验证
        $vConf = array(
            array('custom_id', '商品分类', 'required|is_numeric'),
            array('page', '页码', 'required|is_natural_no_zero'),
            array('order', '排序', 'required|in_list[0,1,2,3,4]'),
        );
        $this->formDataValidation($vConf);
        $customId = (int)post('custom_id');
        $page = (int)post('page');
        $order = (int)post('order');

        //获取商品列表
        $data = $this->mProduct->appGetList($this->userId, $customId, $page, $order, true);

        $this->appReturn(1, '', $data);

    }

    /**
     * 商品自定义排序
     */
    public function productSort(){

        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');

        //表单验证
        $vConf = array(
            array('text', '序列', 'required'),
        );
        $this->formDataValidation($vConf);

        $text = trim(post('text'));
        $tData = json_decode(stripslashes($text), true);

        if(!is_array($tData)){
            $this->appReturn(0, '序列格式错误');
        }
        foreach ($tData as $v){
            if(!is_numeric($v['sort'])){
                $this->appReturn(0, '序号必须是数字');
            }
        }

        //保存排序
        $query = $this->mProduct->saveBatchProduct($tData, 'id');
        if($query === false){
            $this->appReturn(0, '保存失败');
        }

        $this->appReturn(1, '保存成功');
    }

    /**
     * 删除商品
     */
    public function delProduct(){
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        //表单验证
        $vConf = array(
            array('id', '商品id', 'required|is_numeric')
        );
        $this->formDataValidation($vConf);

        $id = post('id');

        //商品是否存在
        $productInfo = $this->mProduct->getInfo($id, $this->userId, false);
        if(!$productInfo){
            $this->appReturn(0, '商品不存在');
        }

        if($productInfo['status'] == 2){
            $this->appReturn(0, '上架商品不可删除');
        }

        if($productInfo['status'] == 0){ //草稿状态的商品
            //删除商品
            if(!($this->mProduct->deleteProduct($id))){
                $this->appReturn(0, '删除失败');
            }
        }

        if($productInfo['status'] == 1){ //下架状态的商品
            //改变商品状态
            if(!($this->mProduct->save(array('status' => -1), $id))){
                $this->appReturn(0, '删除失败');
            }
        }
        $this->appReturn(1, '删除成功');
    }


}